package cc.rengu.redp.bizimpl.upmp.service.impl;

/*import cc.rengu.ecp.core.exception.ServiceException;
import cc.rengu.ecp.core.pagination.PropertyFilter;
import cc.rengu.ecp.core.util.Common;
import cc.rengu.ecp.core.util.GZIPUtils;
import cc.rengu.ecp.platform.core.security.AuthContextHolder;
import cc.rengu.ecp.platform.mcmp.dao.MarketingAdsDao;
import cc.rengu.ecp.platform.module.auth.entity.User;*/

import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.MarketingAdsMapper;
import cc.rengu.redp.bizimpl.upmp.domain.MarketingAds;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpOrganization;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.IMarketingAdsService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpOrganizationService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpPrivilegeCheckService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.MarketingAdsQueryVO;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.bizimpl.utils.GZIPUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.codec.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 对MarketingAds实体提供服务
 *
 * @author yuhongwen
 * @date 2020年04月08日05时12分
 * @see
 */

@Slf4j
@Service
@DS("upmp")
public class MarketingAdsServiceImpl extends ServiceImpl<MarketingAdsMapper, MarketingAds> implements IMarketingAdsService {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Autowired
    private IUpmpOrganizationService organizationService;

    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;

    @Override
    public OperationResult saveData(String oprMenuId, String oprMenuName, MarketingAds entity, String webNextUrl, String[] imgSrc, String[] dataId, String[] imgThumbSrc, String[] imgNo, String[] imgTm, String mainDataId, String adType) {
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        //
        String flag = entity.getOptFlag();
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        String instId = entity.getInstId();
        String crtOrgId = "";

        if (flag.equals("add") && user.isAdmin()) {
            if (StringUtils.isEmpty(instId)) {
                log.error("保存数据时请先选择法人行!");
                return OperationResult.buildFailureResult("保存数据时请先选择法人行!");
            } else {
                UpmpOrganization headOrg = organizationService.getHeadOrgByCode(instId);
                crtOrgId = (headOrg == null ? user.getOrgCode() : headOrg.getOrgCode());
            }
        } else {
            instId = (instId == null ? user.getInstId() : instId);
            crtOrgId = (StringUtils.isBlank(entity.getCrtOrgId()) ? user.getOrgCode() : entity.getCrtOrgId());
        }
        UpmpOrganization org = organizationService.getOrgByCode(crtOrgId, instId);
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)) {
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), oprMenuName + ":增加");
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //需要审核
            } else {
                //不需要审核
                int num = 0;
                List<MarketingAds> list = findMarketingAds(instId, entity.getAdType(), entity.getMainDataId());
                if (list.size() > 0) {
                    return OperationResult.buildFailureResult("数据重复不能添加!", result);
                }
                mainDataId = CommonUtils.getUUID();
                for (int i = 0; i < imgSrc.length; i++) {
                    MarketingAds MarketingAds = new MarketingAds();
                    if (null != imgSrc[i] && !imgSrc[i].equals("")) {
                        MarketingAds.setAdType(entity.getAdType());
                        MarketingAds.setAdDesc(entity.getAdDesc());
                        MarketingAds.setBeginTime(entity.getBeginTime());
                        MarketingAds.setExpireTime(entity.getExpireTime());
                        MarketingAds.setMarketingPagePath(entity.getMarketingPagePath());
                        MarketingAds.setId(null);
                        MarketingAds.setOprId(user.getUserId());
                        MarketingAds.setCrtOrgId(org.getOrgCode());
                        MarketingAds.setCreateTime(lastUpddt);
                        MarketingAds.setInstId(instId);
                        MarketingAds.setStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                        if (entity.getAdType().equals("00")) {
                            MarketingAds.setPushAdModule("01");
                        } else {
                            MarketingAds.setPushAdModule(entity.getPushAdModule());
                        }

                        MarketingAds.setImageLocalPath(Base64.decodeToString(imgSrc[i]));
                        if (null != imgNo[i] && !imgNo[i].equals("")) {
                            MarketingAds.setImageIndex(Integer.parseInt(imgNo[i]));
                        } else {
                            MarketingAds.setImageIndex(0);
                        }
                        if (null != imgTm && null != imgTm[i] && !imgTm[i].equals("")) {
                            MarketingAds.setPlayTm(imgTm[i]);
                        }
                        MarketingAds.setThumbnailPath(imgThumbSrc[i]);
                        MarketingAds.setMainDataId(mainDataId);
                        this.save(MarketingAds);
                        num++;
                    }
                }
                if (num == 0) {
                    return OperationResult.buildFailureResult("请至少添加一个图片!", result);
                }

//                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());


//                bizTmpService.saveBizHis(entity, user, org, BizOprEnum.OPR_ADD.getType(), lastUpddt
//                        , oprMenuId, oprMenuName, String.valueOf(entity.getId()));
                result.put("mainDataId", mainDataId);
            }
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)) {

            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), oprMenuName + ":修改");
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //需要审核

            } else {
                String push = "";
                if (entity.getAdType().equals("00")) {
                    push = "01";
                } else {
                    push = entity.getPushAdModule();
                }
                /*
                TODO: 不知道这个判重的意义，先注释掉，否则无法校验通过
                List<MarketingAds> list = findMarketingAds(entity.getInstId(), entity.getAdType(), entity.getMainDataId());
                if (list.size() > 0) {
                    boolean repeat = false;
                    out:
                    for (MarketingAds ads : list) {
                        for (int k = 0; k < dataId.length; k++) {
                            if (ads.getId().equals(dataId[k])) {
                                break;
                            }
                            if (k == dataId.length - 1) {
                                repeat = true;
                                break out;
                            }
                        }
                    }
                    if (repeat) {
                        return OperationResult.buildFailureResult("数据重复不能修改!", result);
                    }
                }*/
                deleteMarketingAds(entity.getInstId(), adType, mainDataId);
                for (int i = 0; i < imgSrc.length; i++) {
                    MarketingAds MarketingAds = new MarketingAds();
                    if (null != imgSrc[i] && !imgSrc[i].equals("")) {
                        MarketingAds.setAdType(entity.getAdType());
                        MarketingAds.setAdDesc(entity.getAdDesc());
                        MarketingAds.setBeginTime(entity.getBeginTime());
                        MarketingAds.setExpireTime(entity.getExpireTime());
                        MarketingAds.setMarketingPagePath(entity.getMarketingPagePath());
                        MarketingAds.setId(null);
                        MarketingAds.setOprId(user.getUserId());
                        MarketingAds.setCrtOrgId(org.getOrgCode());
                        MarketingAds.setCreateTime(lastUpddt);
                        MarketingAds.setInstId(instId);
                        MarketingAds.setStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                        if (entity.getAdType().equals("00")) {
                            MarketingAds.setPushAdModule("01");
                        } else {
                            MarketingAds.setPushAdModule(entity.getPushAdModule());
                        }
                        MarketingAds.setImageLocalPath(imgSrc[i]);
                        if (null != imgNo[i] && !imgNo[i].equals("")) {
                            MarketingAds.setImageIndex(Integer.parseInt(imgNo[i]));
                        } else {
                            MarketingAds.setImageIndex(0);
                        }
                        if (null != imgTm && null != imgTm[i] && !imgTm[i].equals("")) {
                            MarketingAds.setPlayTm(imgTm[i]);
                        }
                        MarketingAds.setThumbnailPath(imgThumbSrc[i]);
                        MarketingAds.setMainDataId(mainDataId);
                        this.save(MarketingAds);
                        result.put("mainDataId", mainDataId);
                    }
                }
                //updMarketingAds(entity.getInstId(),adType,mainDataId,entity.getAdType(),entity.getAdDesc(),entity.getMarketingPagePath(),push);
//                bizTmpService.saveBizHis(marketingAds, user, org, BizOprEnum.OPR_UPDATE.getType(), lastUpddt
//                        , oprMenuId, oprMenuName, String.valueOf(marketingAds.getId()));
            }
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(flag)) {

        } else {
            log.info("类名-方法名", "MarketingAdsService-" + "saveData");
        }

        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }


    public List<MarketingAds> findMarketingAds(String instId, String adType, String mainDataId) {
        LambdaQueryWrapper<MarketingAds> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MarketingAds::getInstId, instId);
        wrapper.eq(MarketingAds::getAdType, adType);
        wrapper.eq(MarketingAds::getMainDataId, StringUtils.isNotBlank(mainDataId) ? mainDataId : "");
        wrapper.orderByAsc(MarketingAds::getImageIndex);
        return baseMapper.selectList(wrapper);
    }


    public void updMarketingAds(String instId, String adType, String mainDataId, String adType1, String adDesc, String marketingPagePath, String push) throws RedpException {
        LambdaQueryWrapper<MarketingAds> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MarketingAds::getInstId, instId);
        wrapper.eq(MarketingAds::getAdType, adType);
        wrapper.eq(MarketingAds::getMainDataId, mainDataId);
        MarketingAds params = this.getOne(wrapper);
        if (params == null) {
            throw new RedpException("数据不存在");
        } else {
            params.setAdType(adType1);
            params.setAdDesc(adDesc);
            params.setMarketingPagePath(marketingPagePath);
            params.setPushAdModule(push);

            this.updateById(params);
        }
    }

    public void deleteMarketingAds(String instId, String adType, String mainDataId) {
        LambdaQueryWrapper<MarketingAds> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MarketingAds::getInstId, instId);
        wrapper.eq(MarketingAds::getAdType, adType);
        wrapper.eq(MarketingAds::getMainDataId, mainDataId);
        this.baseMapper.delete(wrapper);
    }

    public void releaseMarketingAds(String instId, String adType, String mainDataId) throws RedpException {
        String isuTm = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        LambdaQueryWrapper<MarketingAds> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MarketingAds::getInstId, instId);
        wrapper.eq(MarketingAds::getAdType, adType);
        wrapper.eq(MarketingAds::getMainDataId, mainDataId);
        List<MarketingAds> params = this.list(wrapper);
        if (params == null) {
            throw new RedpException("数据不存在");
        } else {
            for (MarketingAds param : params) {
                param.setIsuId(user.getUserId());
                param.setIsuTm(isuTm);
                param.setStatus("01");
                this.updateById(param);
            }
        }
    }

    public IPage<MarketingAds> marketingAdsSelectList(QueryRequest request, MarketingAdsQueryVO vo) {
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String userOrgCodes = GZIPUtils.uncompressToString(user.getUserOrgCodes());

        String adDesc = vo.getAdDesc();
        String instId = vo.getInstId();
        String startTime = vo.getStartTime();
        String endTime = vo.getEndTime();
        String adStatus = vo.getAdStatus();
        if (Common.isBlank(instId)) {
            instId = user.getInstId();
        }

        LambdaQueryWrapper<MarketingAds> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(adDesc)) {
            queryWrapper.like(MarketingAds::getAdDesc, adDesc);
        }
        if (Common.isNotBlank(startTime)) {
            startTime = startTime + ":00";
            queryWrapper.ge(MarketingAds::getCreateTime, startTime);
        }
        if (Common.isNotBlank(endTime)) {
            endTime = endTime + ":00";
            queryWrapper.le(MarketingAds::getCreateTime, endTime);
        }
        if (Common.isNotBlank(adStatus)) {
            queryWrapper.eq(MarketingAds::getStatus, adStatus);
        }
        if (null != user && user.isAdmin()) {
            if (StringUtils.isBlank(instId)) {
                instId = user.getInstId();
            }
            queryWrapper.eq(MarketingAds::getInstId, instId);
        } else {
//            String[] userOrgCodeArray = userOrgCodes.split(",");
//            List<String> userOrgCodeList = Arrays.asList(userOrgCodeArray);
//            queryWrapper.in(MarketingAds::getCrtOrgId, userOrgCodeList);
        }
        queryWrapper.select(MarketingAds::getInstId, MarketingAds::getAdType, MarketingAds::getMarketingPagePath,
                MarketingAds::getCreateTime, MarketingAds::getBeginTime, MarketingAds::getExpireTime, MarketingAds::getAdDesc, MarketingAds::getStatus, MarketingAds::getMainDataId, MarketingAds::getIsuId, MarketingAds::getIsuTm);
        queryWrapper.groupBy(MarketingAds::getInstId, MarketingAds::getAdType, MarketingAds::getMarketingPagePath,
                MarketingAds::getCreateTime, MarketingAds::getBeginTime, MarketingAds::getExpireTime, MarketingAds::getAdDesc, MarketingAds::getStatus, MarketingAds::getMainDataId, MarketingAds::getIsuId, MarketingAds::getIsuTm);
//        sql.append(" group by INST_ID, AD_TYPE,MARKETING_PAGE_PATH, CREATE_TIME,BEGIN_TIME,EXPIRE_TIME, AD_DESC, STATUS,MAIN_DATA_ID,ISU_ID,ISU_TIME");
        Page<MarketingAds> page = new Page<>();
        SortUtil.handlePageSort(request, page, true);

        return this.page(page, queryWrapper);
    }
}
